<template>
  <div class="activity">
    <div class="activity-header">
      <el-row>
        <el-col>
          <el-button
            type="primary"
            v-btnpermission="'btn-activityadd'"
            @click="setData('add')"
            >新增</el-button
          >
          <!-- 导入 -->
          <!-- <el-button type="primary">导入</el-button> -->
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="formSearch.startTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="formSearch.endTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="活动名称">
            <el-input v-model="formSearch.name" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="activity-list">
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="activityList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>

            <el-table-column prop="Name" label="活动名称"></el-table-column>
            <el-table-column
              prop="StartTime"
              label="开始时间"
              :formatter="timeFormat"
            ></el-table-column>
            <el-table-column
              prop="EndTime"
              label="结束时间"
              :formatter="timeFormat"
            ></el-table-column>
            <el-table-column prop="Remarks" label="备注"></el-table-column>

            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-activityupdate'"
                  :icon="Edit"
                  @click="setData('edit', scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-activitydelete'"
                  @click="rowDelete(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        :title="dialogType == 'add' ? '新增' : '修改'"
        v-model="addDialogVisible"
        width="50%"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogForm"
          :rules="activityFormRulesMixin.addFormRules"
          ref="addDialogRef"
          label-width="80px"
          inline
        >
          <el-form-item label="活动名称" prop="Name">
            <el-input v-model="addDialogForm.Name" />
          </el-form-item>
          <el-form-item label="经度" prop="Lng">
            <el-input-number
              v-model="addDialogForm.Lng"
              :precision="7"
              size="large"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="Lat">
            <el-input-number
              v-model="addDialogForm.Lat"
              :precision="7"
              size="large"
            />
          </el-form-item>
          <el-form-item label="开始时间" prop="StartTime">
            <el-date-picker
              v-model="addDialogForm.StartTime"
              type="datetime"
              placeholder="--请选择--"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="EndTime">
            <el-date-picker
              v-model="addDialogForm.EndTime"
              type="datetime"
              placeholder="--请选择--"
            />
          </el-form-item>
          <el-form-item prop="Remarks" label="备注">
            <el-input v-model="addDialogForm.Remarks" />
          </el-form-item>
          <el-form-item label="缩放级别" prop="ZoomLevel">
            <el-input-number v-model="addDialogForm.ZoomLevel" />
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { activityFormRulesMixin } from '@/utils/mixin.js';
import {
  getActivityList,
  addActivity,
  editActivity,
  delActivity,
} from '@/network/activity.js';
import { ref, reactive, onBeforeMount } from 'vue';
// import { getDicByDictionary, getDicByTableName } from "@/network/dictionary.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import moment from 'moment';
// 搜索条件
const formSearch = reactive({
  name: '',
  startTime: getInitTime(60),
  endTime: getInitTime(),
  total: 0,
  page: 1,
  pageSize: 10,
});
function timeFormat(row, column, v, i) {
  return moment(String(v)).format('YYYY-MM-DD hh:mm:ss');
}
function getInitTime(intday, hour) {
  let secodenpast = new Date().getTime() - (intday || 0) * 24 * 60 * 60 * 1000;
  var now = new Date(secodenpast);
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  hour = hour || ' 00:00:00'; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
  month = month + 1;
  month = month.toString().padStart(2, '0');
  date = date.toString().padStart(2, '0');
  let x = `${year}-${month}-${date}${hour}`;
  return x;
}
const dialogType = ref('');
//新增、修改
const setData = (type, row) => {
  dialogType.value = type;
  addDialogVisible.value = true;
  type == 'add'
    ? (addDialogForm.value = {})
    : (addDialogForm.value = { ...row });
};
//初始化
let activityList = ref(null);
const initData = async () => {
  let params = {
    name: formSearch.name,
    startTime: formSearch.startTime,
    endTime: formSearch.endTime,
    page: formSearch.page,
    pageSize: formSearch.pageSize,
  };
  await getActivityList(params).then((res) => {
    activityList.value = res.data;
    formSearch.total = res.total;
  });
};
//初始化字典
const initDict = async () => {};
onBeforeMount(() => {
  initData();
  initDict();
});
//新增
const addDialogVisible = ref(false);
const addDialogRef = ref(null);
let addDialogForm = ref({
  Name: '',
  Lng: '',
  Lat: '',
  StartTime: '',
  EndTime: '',
  Remarks: '',
  ZoomLevel: '',
});
const addFormSubmit = async () => {
  await addDialogRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogType.value == 'add') {
        await addActivity(addDialogForm.value)
          .then(() => {
            addDialogVisible.value = false;
            initData();
            ElMessage.success('新增成功');
          })
          .catch(() => {
            ElMessage.error('新增失败');
          });
      } else {
        await editActivity(addDialogForm.value)
          .then(() => {
            addDialogVisible.value = false;
            initData();
            ElMessage.success('修改成功');
          })
          .catch(() => {
            ElMessage.error('修改失败');
          });
      }
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
const addDislogClosed = () => {
  // addDialogForm.value = {};
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};

//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await delActivity({ code: id })
        .then(() => {
          initData();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
//搜索
const onSubmit = async () => {
  formSearch.page = 1;
  await initData();
};
//重置
const onReset = async () => {
  formSearch.name = '';
  formSearch.page = 1;
  formSearch.startTime = getInitTime(60);
  formSearch.endTime = getInitTime();
  await initData();
};
//分页
const handleCurrentChange = async (val) => {
  formSearch.page = val;
  await initData();
};
</script>

<style lang="scss" scoped>
.activity {
  margin: 14px 15px 14px;
  .activity-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .activity-list {
    margin-top: 14px;
  }
}
</style>
